//
//  PywIAPHelper.m
//  PywSdk
//
//  Created by Jade on 16/7/26.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywIAPHelper.h"
#import "Pyw_IAPHelper.h"
#import "PywIAPShare.h"
#import "NSString+PywBase64.h"
#import "AIFCheckApplePayManager.h"
#import "PropertyListReformer.h"
#import "PywSdk+pay.h"
#import "PywCPNotifications.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywAppleReceipt.h"

@interface PywIAPHelper()<ETAPIManagerCallBackDelegate>
@property (nonatomic,strong) AIFCheckApplePayManager *manager;

@end
@implementation PywIAPHelper
+ (instancetype)manager
{
    static id manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] init];
    });
    return manager;
}

- (AIFCheckApplePayManager *)manager
{
    if (!_manager) {
        _manager = [AIFCheckApplePayManager manager];
        _manager.delegate = self;
    }
    return _manager;
}

#pragma mark - Public Action
/**
 *  添加苹果内购监听
 */
- (void)addTransactionObserver
{
    WEAK_SELF;
    [PywIAPShare sharedHelper].iap = [[Pyw_IAPHelper alloc] initWithCompletion:^(SKPaymentTransaction *transcation) {
        
        [weakSelf payFinish:transcation];
    }];
}

/**
 *  验证之前没有验证成功的支付订单
 */
- (void)checkLocalApplePay
{
    @try {
        [self addTransactionObserver];
        
        NSArray *receipts = [PywAppleReceipt receipts];
        for (PywAppleReceipt *appleReceipt in receipts) {
            if (appleReceipt.receipt.length > 0) {
                self.manager.order_no = appleReceipt.orderNum;
                self.manager.receipt = appleReceipt.receipt;
                self.manager.order_account = appleReceipt.account;
                [self.manager loadData];
            }else {
//                [PywAppleReceipt removeReceipt:appleReceipt.orderNum];
            }
            
        }
    } @catch (NSException *exception) {
        PLog(@"验证票据失败");
    } @finally {
        
    }
}


/**
 *  购买
 *
 *  @param productId <#productId description#>
 */
- (void)startBuyProduct:(NSString *)productId
               orderNum:(NSString *)orderNum
{
    @try {
        [PywMBProgressHUD showMessage:@"正在支付..." toView:[UIApplication sharedApplication].keyWindow];
        /**
         *  保存订单号和计费点
         */
        [self cacheReceipt:orderNum
                 productId:productId
                   account:[PywPlatformMain sharedPlatformMain].account];
        
        NSSet* dataSet = [[NSSet alloc] initWithObjects:productId, nil];
        [PywIAPShare sharedHelper].iap = [[Pyw_IAPHelper alloc] initWithProductIdentifiers:dataSet];
        WEAK_SELF;
        [[PywIAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
         {
             if(response > 0 && [PywIAPShare sharedHelper].iap.products.count > 0) {
                 
                 SKProduct* product =[[PywIAPShare sharedHelper].iap.products objectAtIndex:0];
                 /**
                  *  product 计费点
                  *  orderNum 订单号
                  *  account 用户
                  */
                 [[PywIAPShare sharedHelper].iap buyProduct:product
                                                orderNum:orderNum
                                                 account:[PywPlatformMain sharedPlatformMain].account
                                            onCompletion:^(SKPaymentTransaction* trans){
                                                STRONG_SELF(weakSelf);
                                                [strongSelf payFinish:trans];
                                                
                                            }];//end of buy product
             }else {//获取商品信息失败
                 STRONG_SELF(weakSelf);
                 [strongSelf payFailWithError:@"获取不到商品信息" productId:productId orderNum:nil account:nil];
             }
         }];
    } @catch (NSException *exception) {
        PLog(@"苹果内购失败");
    } @finally {
        
    }
}

/**
 *  苹果内购支付完成
 */
- (void)payFinish:(SKPaymentTransaction *)trans
{
    NSString *productId = trans.payment.productIdentifier;
    NSArray *params = [trans.payment.applicationUsername componentsSeparatedByString:@"|"];
    NSString *account = @"";
    NSString *orderNum = @"";
    if (params.count > 1) {
        orderNum = [params firstObject];
        account = [params lastObject];
    }
    if(trans.error)//苹果返回报错信息
    {
        PLog(@"Fail %@",[trans.error localizedDescription]);
        NSString *message = [NSString stringWithFormat:@"支付失败:%@",[trans.error localizedDescription]];
        [self payFailWithError:message
                       productId:productId
                        orderNum:orderNum
                         account:account];
    }
    else if(trans.transactionState == SKPaymentTransactionStatePurchased) {//支付成功
        
        [self paySuccessAndCheckApplePayWithReceipt:trans
                                             orderNum:orderNum
                                              account:account
                                            productId:productId];
    }
    else if(trans.transactionState == SKPaymentTransactionStateFailed) {//支付失败
        
        [self payFailWithError:@"支付失败"
                       productId:productId
                        orderNum:orderNum
                         account:account];
    }
}

/**
 *  苹果支付成功
 */
- (void)paySuccessAndCheckApplePayWithReceipt:(SKPaymentTransaction *)trans
                                     orderNum:(NSString *)orderNum
                                      account:(NSString *)account
                                    productId:(NSString *)productId
{
    //获取票据
    NSString *receipt = [NSString base64StringFromData:trans.transactionReceipt
                                                length:[trans.transactionReceipt length]];
    
    
    /**
     *  匹配插入票据
     */
    [self matchToInsertReceipt:receipt
                      orderNum:orderNum
                       account:account
                     productId:productId];
    //上传票据
    if (orderNum.length > 0) {
        [self requestVerfyReceipt:orderNum
                          receipt:receipt
                          account:account];
    }
    [PywMBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                        object:@"支付完成"];
}

/**
 *  苹果支付失败
 */
- (void)payFailWithError:(NSString *)message
               productId:(NSString *)productId
                orderNum:(NSString *)orderNum
                 account:(NSString *)account
{
    //匹配删除订单号信息
    [self matchToDeleteReceipt:productId
                      orderNum:orderNum
                       account:account];
    
    [PywMBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                            object:message];
    });
}



#pragma mark - 票据相关处理

/**
 *  缓存订单号和计费点
 */
- (void)cacheReceipt:(NSString *)orderNum
           productId:(NSString *)productId
             account:(NSString *)account
{
    PywAppleReceipt *appleReceipt = [[PywAppleReceipt alloc] init];
    appleReceipt.orderNum = orderNum;
    appleReceipt.productId = productId;
    appleReceipt.account = account;
    [PywAppleReceipt saveReceipt:appleReceipt];
}

/**
 *  支付成功：匹配并插入票据
 *  返回匹配到的订单号
 */
- (NSString *)matchToInsertReceipt:(NSString *)receipt
                          orderNum:(NSString *)orderNum
                           account:(NSString *)account
                   productId:(NSString *)productId
{
    NSArray *receipts = [PywAppleReceipt receipts];
    for (PywAppleReceipt *appleReceipt in receipts) {
        if ([appleReceipt.productId isEqualToString:productId]
            && appleReceipt.receipt.length == 0
            && [appleReceipt.account isEqualToString:account]
            && [appleReceipt.orderNum isEqualToString:orderNum]) {
            appleReceipt.receipt = receipt;
            [PywAppleReceipt saveReceiptList:receipts];
            return appleReceipt.orderNum;
        }
    }
    return nil;
}

/**
 *  支付失败：匹配并删除票据
 */
- (void)matchToDeleteReceipt:(NSString *)productId
                    orderNum:(NSString *)orderNum
                     account:(NSString *)account
{
    NSArray *receipts = [PywAppleReceipt receipts];
    for (PywAppleReceipt *appleReceipt in receipts) {
        if ([appleReceipt.productId isEqualToString:productId]
            && appleReceipt.receipt.length == 0
            && [appleReceipt.account isEqualToString:account]
            && [appleReceipt.orderNum isEqualToString:orderNum]) {
            [PywAppleReceipt removeReceipt:appleReceipt.orderNum];
            return;
        }
    }
}

#pragma mark - 上传苹果票据
/**
 *  验证苹果票据
 */
- (void)requestVerfyReceipt:(NSString *)order_no
                    receipt:(NSString *)receipt
                    account:(NSString *)account
{
    self.manager.order_no = order_no;
    self.manager.receipt = receipt;
    self.manager.order_account = account;
    [self.manager loadData];
}

#pragma mark - 上传票据完成

- (void)managerCallAPIDidSuccess:(ETApiBaseManager *)manager
{
    PropertyListReformer *reformer = [[PropertyListReformer alloc] init];
    NSDictionary *dict = [manager fetchDataWithReformer:reformer];
    NSString *ack = [dict objectForKey:@"ack"];
    if ([ack intValue] == 200) {
        NSString *order_no = [[dict objectForKey:@"data"] objectForKey:@"order_no"];
        if (order_no.length > 0) {
            [PywAppleReceipt removeReceipt:order_no];
        }
    }
    
    
}


- (void)managerCallApiDidFailed:(ETApiBaseManager *)manager{
//    [PywMBProgressHUD showError:@"请求失败"];
}

@end
